<?php
/**
 * Created by PhpStorm.
 * Script Name: AppInit.php
 * Create: 2022/9/19 19:15
 * Description:
 * Author: fudaoji<fdj@kuryun.cn>
 */

namespace plugin\wechat\app\platform\middleware;

use app\common\service\App;

use plugin\wechat\app\service\Bot as BotService;
use plugin\wechat\app\service\Mp as MpService;
use plugin\wechat\app\service\Mini as MiniService;
use plugin\wechat\app\service\OpenPlatform as OpenPlatformService;
use Webman\Http\Request;
use Webman\Http\Response;
use Webman\MiddlewareInterface;

class AppInit implements MiddlewareInterface
{
    /**
     * @inheritDoc
     */
    public function process(Request $request, callable $handler): Response
    {
        $app        = request()->getApp();
        $controller = request()->getController();
        $action     = request()->getAction();

        $controller_layer = explode('/', $controller);
        $controller = strtolower($controller_layer[count($controller_layer) - 1]);
        $request->controller = $controller;
        $request->appInfo = App::getApp($request->plugin);
        $request->appId = input('appid', '');
        $request = self::setMpInfo($request);
        $request = self::setApp($request);

        return $handler($request);
    }

    /**
     * 设置微信公众号/小程序信息
     * @param $request
     * @return
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * @author fudaoji<fdj@kuryun.cn>
     */
    static function setMpInfo(Request $request) {
        if($request->appId){
            if(! $request->mpInfo = MpService::getInfo($request->appId)){
                $request->mpInfo = MiniService::getInfo($request->appId);
            }
        }
        return $request;
    }

    /**
     * 设置授权公众号/小程序应用
     * @param Request $request
     * @return Request
     * @throws \Psr\SimpleCache\InvalidArgumentException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * Author: fudaoji<fdj@kuryun.cn>
     */
    protected function setApp(Request $request) {
        if($request->mpInfo) {
            $request->mpApp = isset($this->mpInfo['mini_program_info'])
                ? MiniService::getApp($request->mpInfo, $request)
                : MpService::getApp($request->mpInfo, $request);
        }
        $request->openPlatform = OpenPlatformService::getOpenPlatform();
        return $request;
    }
}